from .base_strategy import BaseStrategy
import backtrader as bt
import backtrader.indicators as btind
import indicator.MyTTIndicator as Mytt
import indicator.myzhibiao as mmm


###
# RSI25 金叉死叉 RSI150 从而判断做多 做空
# 金叉做多，死叉开空
# 但是 实测效果并不理想
# #
class MyStrategy(BaseStrategy):
    params = (
        ('ema_short', 120),  # EMA120
        ('rsi_short', 25),   # RSI25
        ('rsi_long', 150),   # RSI150 (注意：通常RSI范围是0-100，这里可能是笔误，应该是RSI14或其他值)
        ('stop_loss_pct', 30),  # 10% 止损
        ('risk_factor', 0.1),  # 开仓比例  50%
    )
 
    def __init__(self):
        super().__init__()

        self.init_indicators()

        # 跟踪订单和交易状态
        self.order = None
        self.trade_count = 0
        self.current_position = 0  # 0: 无仓位, 1: 多头, -1: 空头
        self.stop_price = 0  # 止损价格

    def init_indicators(self):
        """在此定义指标 (EMA/MACD/RSI等)"""
        self.ema = btind.EMA(self.data.close, period=self.p.ema_short)
        self.rsi_short = btind.RSI(self.data.close, period=self.p.rsi_short)
        self.rsi_long = btind.RSI(self.data.close, period=self.p.rsi_long) 
         # 交叉信号指标
        self.cross_up = btind.CrossUp(self.rsi_short, self.rsi_long)
        self.cross_down = btind.CrossDown(self.rsi_short, self.rsi_long)


    def notify_order(self, order):
        super().notify_order(order)

    def notify_trade(self, trade):
        super().notify_trade(trade)

    def next(self):
        super().next()

        duotou = self.data.close[-1] < self.ema[0] and self.cross_up[0]
        kongtou = self.data.close[-1] > self.ema[0] and self.cross_down[0]

        # 检查是否已经有仓位
        if not self.position:  # 无仓位
            # 计算可用的交易资金
            available_cash = self.broker.getvalue() * self.p.risk_factor
            # 计算可买入的合约数量
            size = available_cash / self.data.close[0]
            # 做多条件：收盘价低于EMA120且RSI25上穿RSI150
            if duotou:
                self.stop_price = self.data.close[0] * (1 - self.p.stop_loss_pct / 100)
                self.log(f'买入信号: 收盘价 {self.data.close[-1]:.6f} < EMA120 {self.ema[0]:.6f}, RSI25上穿RSI150，止损价：{self.stop_price}')
                self.order = self.buy(size=size)
                self.trade_count += 1
                self.current_position = 0

            
            # 做空条件：收盘价高于EMA120且RSI25下穿RSI150
            elif kongtou:
                self.stop_price = self.data.close[0] * (1 + self.p.stop_loss_pct / 100)

                self.log(f'卖出信号: 收盘价 {self.data.close[-1]:.6f} > EMA120 {self.ema[0]:.6f}, RSI25下穿RSI150，止损价：{self.stop_price}')
                self.order = self.sell(size=size)
                self.trade_count += 1
                self.current_position = 0

            elif self.current_position==1:
                self.order = self.buy(size=size)
                self.stop_price = self.data.close[0] * (1 - self.p.stop_loss_pct / 100)
            elif self.current_position==-1:
                self.order = self.sell(size=size)
                self.stop_price = self.data.close[0] * (1 + self.p.stop_loss_pct / 100)


        else:  # 有仓位
            # 设置止损
            if self.position.size > 0 and self.stop_price!=0:  # 多头仓位
                if self.data.close[0] < self.stop_price:
                    self.log(f'止损触发: 多头止损价格 {self.stop_price:.6f}')
                    self.order = self.close()
                    self.stop_price = 0
            
            elif self.position.size < 0 and self.stop_price!=0:  # 空头仓位
                if self.data.close[0] > self.stop_price:
                    self.log(f'止损触发: 空头止损价格 {self.stop_price:.6f}')
                    self.order = self.close()
                    self.stop_price = 0
                    

            
            # 平仓条件（与开仓条件相反）
            # 多头平仓条件：收盘价高于EMA120且RSI25下穿RSI150
            elif self.position.size > 0 and kongtou:
                self.log(f'平多信号: 收盘价 {self.data.close[-1]:.6f} > EMA120 {self.ema[0]:.6f}, RSI25下穿RSI150')
                self.order = self.close()
                # 立即开空
                # self.order = self.sell()
                self.current_position = -1
            
            # 空头平仓条件：收盘价低于EMA120且RSI25上穿RSI150
            elif self.position.size < 0 and duotou:
                self.log(f'平空信号: 收盘价 {self.data.close[-1]:.6f} < EMA120 {self.ema[0]:.6f}, RSI25上穿RSI150')
                self.order = self.close()
                # 立即开多
                # self.order = self.buy()
                self.current_position = 1